package com.faner4cloud.yun.controller;

import cn.hutool.json.JSONUtil;
import com.amazonaws.annotation.NotThreadSafe;
import com.faner4cloud.yun.dao.entity.SysDict;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;


@Slf4j
@NotThreadSafe
@RestController
public class ConcurrencyTest {

	private static final ExecutorService exportExecutor = new ThreadPoolExecutor(4, 4, 0L,
		TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(100), new ThreadFactory() {
		private final AtomicInteger threadNumber = new AtomicInteger(1);

		@SuppressWarnings("NullableProblems")
		@Override
		public Thread newThread(Runnable r) {
			return new Thread(r, "export" + threadNumber.getAndIncrement());
		}
	});

	/**
	 * 数字值
	 */
	private static final int INTEGER_90 = 90;
	private static final int INTEGER_200 = 200;
	private static final int INTEGER_2000 = 2000;

	private static final ThreadPoolExecutor executor = new ThreadPoolExecutor(20, 100, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(1000), Executors.defaultThreadFactory());


	public static void main(String[] args) {
		List<SysDict> sysDicts = new ArrayList<>();
		for (int i = 0; i < 100000; i++) {
			SysDict sysDict = new SysDict();
			sysDict.setId((long) i);
			sysDicts.add(sysDict);
		}
		List<List<SysDict>> partionList = Lists.partition(sysDicts, INTEGER_200);
		for (List<SysDict> cookbookList : partionList) {
			executor.submit(() -> {
				try {
					log.info(JSONUtil.toJsonStr(cookbookList));
				} catch (Exception e) {
					log.error("缓存数据异常", e);
				}
			});
			int activeCount = executor.getActiveCount();
			if (activeCount > INTEGER_90) {
				log.info("线程池快满了，休息处理，activeCount={}", activeCount);
				try {
					Thread.sleep(INTEGER_2000);
				} catch (InterruptedException e) {
					log.error("线程池快满了，休息处理 异常", e);
					Thread.currentThread().interrupt();
				}
			}
		}
	}

}
